<?php

namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Models\WeiXin\WeiXinToken;
use App\Models\WeiXin\WeiXinMenu;
use Style,Site,Auth,Session;

require_once('../app/Vendor/MpWeiXin/MpWeiXin.php');
class MpWeiXinPersonController extends CommonController{
    private $access_token='';//access_token 默认值为空
    /**
     * 创建或更新微信菜单 显示页面
     * @return mixed
     */
    public function modifyMunePerson(){

        $WeiXinMenu = WeiXinMenu::select('jsonvalue')->where('category',0)->first();

        if($WeiXinMenu){
            $WeiXinMenu = json_decode($WeiXinMenu->jsonvalue);
            if($WeiXinMenu->button > 0){
                foreach($WeiXinMenu->button as $k => $v){

                    if(!empty($v->sub_button)){
                        //有子菜单, 主菜单事件事值用空值填充
                        $modifyName[$k] = $v->name;//左边菜单名称
                        $modifyType[$k] = '';//事件类型
                        $modifyKey[$k] = '';//事件值
                    }else{
                        //无子菜单
                        $modifyName[$k] = $v->name;//左边菜单名称
                        $modifyType[$k] = $v->type;//事件类型
                        $modifyKey[$k] = empty($v->key) ? $v->url : $v->key;//事件值
                    }

                }
            }
            $elementName =[0=>'first',1=>'second',2=>'third'];
            $viewDir = 'admin.mp_weixin.modifyWeiXinMenu';
        }else{
            $elementName =[];
            $modifyName =[];
            $modifyType =[];
            $modifyKey =[];
            $viewDir = 'admin.mp_weixin.setWeiXinMenu';
        }

        $elementMuneTip =[0=>'微信左边第一个菜单名称',1=>'微信中间第一个菜单名称',2=>'微信右边第一个菜单名称'];
        $elementListMuneTip =[0=>'左边子菜单名称',1=>'中间子菜单名称',2=>'右边子菜单名称'];
        $formUrl = "admin/menuupdateperson";

        return Style::view($viewDir,compact('WeiXinMenu','elementName','modifyName','modifyType','modifyKey',
        'elementMuneTip','elementListMuneTip','formUrl'));

    }

    /**
     * 创建或更新微信菜单
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function menuUpdatePerson(Request $request){
        $wechatObj = new \MpWeiXin();
        //接收值
        $input  = $request->only('Mune','firstListMune','firstType','firstLink', 'secondListMune','secondType',
                                'secondLink','thirdListMune','thirdType','thirdLink');

        $data = [];
        $data['button'] = [];
        //去除空数据
        foreach($input as $k => $v){
            if(count($v) > 1){
                foreach($v as $vKey => $vValue){
                    if(empty($vValue)){
                        $key = array_search($vValue, $input[$k]);
                        $key !== false ? array_splice($input[$k], $key, 1) : '';
                    }
                }
            }
        }

        for($i=0;$i < count($input['Mune']);$i++){
            //左边第一个菜单
            if($i == 0){
                if(!empty($input['firstType'][0]) && !empty($input['firstLink'][0]) && count($input['firstListMune'])<= 0){
                    //主菜单有事件
                    $data['button'][$i]['type'] = $input['firstType'][$i];
                    $data['button'][$i]['name'] = mb_substr($input['Mune'][$i],0,5,'utf-8');
                    //判断是点击事件或是外链接
                    if($input['firstType'][$i] == 'click'){
                        $data['button'][$i]['key'] = $input['firstLink'][$i];
                    }else{
                        $data['button'][$i]['url'] = $input['firstLink'][$i];
                    }
                    continue;
                }else{
                    //子菜单
                    $data['button'][$i]['name'] = mb_substr($input['Mune'][$i],0,5,'utf-8');//一级菜单名称

                    for($ii = 0;$ii < count($input['firstListMune']);$ii++){
                        $data['button'][$i]['sub_button'][$ii]['type'] = $input['firstType'][$ii];

                        $data['button'][$i]['sub_button'][$ii]['name'] = mb_substr($input['firstListMune'][$ii],0,5,'utf-8');

                        //判断是点击事件或是外链接
                        if($input['firstType'][$ii] == 'click'){
                            $data['button'][$i]['sub_button'][$ii]['key'] = $input['firstLink'][$ii];
                        }else{
                            $data['button'][$i]['sub_button'][$ii]['url'] = $input['firstLink'][$ii];
                        }
                    }
                }
            }

            //中间菜单
            if($i == 1){
                if(!empty($input['secondType'][0]) && !empty($input['secondLink'][0]) && count($input['secondListMune'])<= 0){
                    //主菜单有事件
                    $data['button'][$i]['type'] = $input['secondType'][0];
                    $data['button'][$i]['name'] = mb_substr($input['Mune'][$i],0,5,'utf-8');
                    //判断是点击事件或是外链接
                    if($input['secondType'][0] == 'click'){
                        $data['button'][$i]['key'] = $input['secondLink'][0];
                    }else{
                        $data['button'][$i]['url'] = $input['secondLink'][0];
                    }
                    continue;
                }else{
                    //子菜单
                    $data['button'][$i]['name'] = mb_substr($input['Mune'][$i],0,5,'utf-8');//一级菜单名称

                    for($ii = 0;$ii < count($input['secondListMune']);$ii++){
                        $data['button'][$i]['sub_button'][$ii]['type'] = $input['secondType'][$ii];

                        $data['button'][$i]['sub_button'][$ii]['name'] = mb_substr($input['secondListMune'][$ii],0,5,'utf-8');

                        //判断是点击事件或是外链接
                        if($input['secondType'][$ii] == 'click'){
                            $data['button'][$i]['sub_button'][$ii]['key'] = $input['secondLink'][$ii];
                        }else{
                            $data['button'][$i]['sub_button'][$ii]['url'] = $input['secondLink'][$ii];
                        }
                    }
                }
            }

            //右边菜单
            if($i == 2){
                if(!empty($input['thirdType'][0]) && !empty($input['thirdLink'][0]) && count($input['thirdListMune'])<= 0){
                    //主菜单有事件
                    $data['button'][$i]['type'] = $input['thirdType'][0];
                    $data['button'][$i]['name'] = mb_substr($input['Mune'][$i],0,5,'utf-8');
                    //判断是点击事件或是外链接
                    if($input['thirdType'][0] == 'click'){
                        $data['button'][$i]['key'] = $input['thirdLink'][0];
                    }else{
                        $data['button'][$i]['url'] = $input['thirdLink'][0];
                    }
                    continue;
                }else{
                    //子菜单
                    $data['button'][$i]['name'] = mb_substr($input['Mune'][$i],0,5,'utf-8');//一级菜单名称

                    for($ii = 0;$ii < count($input['thirdListMune']);$ii++){
                        if(!empty($input['thirdType'][$ii]) && !empty($input['thirdListMune'][$ii]) && !empty($input['thirdLink'][$ii])){
                            $data['button'][$i]['sub_button'][$ii]['type'] = $input['thirdType'][$ii];

                            $data['button'][$i]['sub_button'][$ii]['name'] = mb_substr($input['thirdListMune'][$ii],0,5,'utf-8');

                            //判断是点击事件或是外链接
                            if($input['thirdType'][$ii] == 'click'){
                                $data['button'][$i]['sub_button'][$ii]['key'] = $input['thirdLink'][$ii];
                            }else{
                                $data['button'][$i]['sub_button'][$ii]['url'] = $input['thirdLink'][$ii];
                            }
                        }else{
                            continue;
                        }
                    }
                }
            }
        }

        $data = json_encode($data,JSON_UNESCAPED_UNICODE);//中文不转unicode

        //接收token     创建菜单实现
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->tokenValue(0);

        $result =  $wechatObj->pushDate($data,$url);

        $result = json_decode($result,true);

        if($result['errcode'] == 0 && !is_null($result['errcode'])){
           //创建成功
           $request->session()->flash('errcode', 'ok');
           $WeiXinMenu = WeiXinMenu::where('category',0)->first();
           if($WeiXinMenu){
               //更新
               WeiXinMenu::where('category',0)->update(['jsonvalue' => $data]);
           }else{
               //创建
               WeiXinMenu::create(['jsonvalue' => $data,'category' => 0]);
           }
           return redirect('admin/modifymuneperson');
        }else{
           //创建失败
           $request->session()->flash('errcode', 'err');
           return redirect('admin/modifymuneperson');
        }
    }

    /**
     * 获取token,检查时间，提前十分钟更新token
     * @param $catetory
     * @return mixed
     */
    private function tokenValue($catetory){

        $wechatObj = new \MpWeiXin();
        return $wechatObj->checkToken('personal',$catetory);

    }
}